var express = require('express');
var router = express.Router();
var sha1 = require('sha1');
var UserModel = require('../db/models/UserModel');
var sign = require('../utils/sign')

/* GET home page. */
router.get('/', function (req, res, next) {
  // console.log(req.query);
  res.render('index', { title: 'Express' });
});

// 验证服务器
router.get('/auth', function (req, res, next) {
  let { signature, timestamp, nonce, echostr } = req.query;
  let token = 'testweixin';

  let array = [timestamp, nonce, token];
  array.sort(); // 字典排序
  let str = array.join('');
  let resultStr = sha1(str); // 对字符串进行sha1加密

  if (resultStr == signature) {
    res.set('Content-Type', 'text/plain');
    res.send(echostr);
  } else {
    res.send('Error!!!');
  }

});

router.get('/jsapi', async (req, res) => {
  let url = decodeURIComponent(req.query.url);
  let conf = await sign(url);
  console.log('conf', conf);
  res.json(conf);
});

router.post('/reg', function (req, res, next) {
  console.log(req.body);
  let { user, pwd } = req.body;
  let create_time = Date.now();

  // 将用户信息保存到数据库中
  new UserModel({ // 一条具体的数据
    user,
    pwd,
    create_time
  }).save().then(() => {
    res.json({
      code: 1,
      msg: '注册成功'
    });
  })

});


router.get('/user', (req, res, next) => {
  console.log(req.query.name);
  UserModel.findOne({ name: req.query.name }, 'name', (err, user) => {
    if (err) throw err;
    console.log(user);
  })
});

module.exports = router;
